package com.alibaba.pet.service.impl;

import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.pet.domain.PetType;
import com.alibaba.pet.mapper.PetTypeMapper;
import com.alibaba.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> getTypeTree() {
        //查询所有宠物类型
        List<PetType> petTypes = petTypeMapper.findAll();
        //将所有宠物类型和id放入map中
        Map<Long, PetType> map = new HashMap<>();
        for (PetType petType : petTypes) {
            map.put(petType.getId(),petType);
        }
        //前段需要的宠物类型树集合数据
        List<PetType> deptTree = new ArrayList<>();
        //遍历查询到的所有宠物类型
        for (PetType petType : petTypes) {
            //没有父类parent_id的话 就是顶级类型，直接添加
            if (petType.getPid() == null){
                //将顶级类型添加到无线级数
                deptTree.add(petType);
            } else {
                //   父类类型         根据子类ID获取子类值  获取子类ID
                PetType parentType = map.get(petType.getPid());
                //父类类型   获取子类       把子类添加进去
                parentType.getChildren().add(petType);
            }
        }
        return deptTree;
    }
}
